package com.example.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import com.example.demo.dto.CaptchaDto;
import com.example.demo.service.RedisService;
import com.example.demo.util.Result;
import com.example.demo.vo.CaptchaVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.util.UUID;

@RestController
@RequestMapping
@Slf4j
public class CaptchaController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/captcha")
    public Result<CaptchaVo> getCaptcha(HttpServletResponse response) throws Exception {
        // 创建一个线型验证码实例
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);

        /*
         设置验证码内容和输出http响应
         */

        // 获取验证码文本内容
        //        String code = captcha.getCode();
        //        log.info("code:{}", code);
        //        // 数据存入redis
        //        redisService.setCaptcha(UUID.randomUUID().toString(), code);
        // 输出图片到response
        // captcha.write(response.getOutputStream());

        String code = captcha.getCode();
        log.info("code:{}", code);

        String uuid = UUID.randomUUID().toString();

        // 数据存入redis
        redisService.setCaptcha(uuid, code);

        // 转base64
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        captcha.write(outputStream);
        byte[] imgBytes = outputStream.toByteArray();
        String base64 = Base64.encode(imgBytes);

        CaptchaVo captchaVo = new CaptchaVo();
        captchaVo.setCaptchaId(uuid);
        captchaVo.setBase64(base64);

        return Result.success(captchaVo);
    }

    @GetMapping("/captcha/valid")
    public Result<Boolean> validateCaptcha(@RequestBody CaptchaDto captchaDto) {
        log.info("captchaDto:{}", captchaDto);
        String code = redisService.getCaptcha(captchaDto.getCaptchaId());
        log.info("code:{}", code);
        return Result.success(code.equals(captchaDto.getCaptchaCode()));
    }

}